package models
/*********************************************************/
/********************本文档为数据库结构文档******************/
/********************IP的数据结构**************************/
/*********************version:1.0*************************/
/****Copyright (c) 2014年 许剑华. All rights reserved******/
/*********************************************************/
import (
	"github.com/astaxie/beego/orm"
	"time"
	"fmt"
	//"github.com/astaxie/beego/validation"
)
type IP struct {
	Id          	int64		`orm:"unique;auto"`
	NewIP			string
	Enable			bool
	TimeStamp		time.Time	`orm:"auto_now_add;type(datetime)"`
	User    		*User   	`orm:"rel(fk)"`
}


func (u *IP) TableName() string {
	return "device_ip"
}

func init() {
	// 需要在init中注册定义的model
	orm.RegisterModel(new(IP))
}
//添加用户
func AddIP(ip *IP,user *User) (error) {

	o := orm.NewOrm()
	ip_tmp := new(IP)
	ip_tmp.NewIP = ip.NewIP
	ip_tmp.User = user


	//	user.Nickname = u.Nickname
	//	user.Email = u.Email
	//	user.Remark = u.Remark
	//	user.Status = u.Status

	_, err := o.Insert(ip_tmp)
	fmt.Println("user:",ip_tmp)
	return err
}




//添加用户
func UpdateIP(ip *IP,user *User) ( error) {

	o := orm.NewOrm()
	ip_tmp := new(IP)
	ip_tmp.NewIP = ip.NewIP
	ip_tmp.User = user

	fmt.Println("user:",user)
	fmt.Println("UserName:",user.UserName)
	//	user.Nickname = u.Nickname
	//	user.Email = u.Email
	//	user.Remark = u.Remark
	//	user.Status = u.Status

	_, err := o.Update(&ip_tmp)
	return err
}
//添加用户
func GetLastIP(user *User) (ip_tmp IP, err error) {
	o := orm.NewOrm()
	err = o.QueryTable("device_ip").One(&ip_tmp)
	if err == orm.ErrNoRows {
		newIP := new(IP)
		newIP.NewIP = "0.0.0.0"
		newIP.Enable = false
		err= AddIP(newIP,user)
	}

	return ip_tmp,err
}
